/**
 * 客户档案管理模块JavaScript
 * 基于Apple交互设计规范的客户管理功能
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let currentCustomerId = null;
let currentSort = { field: 'created_at', order: 'desc' };
let currentFilters = {};
let currentPage = 1;
let pageSize = 20;

// DOM内容加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    loadCustomerList();
    initializeSearch();
    initializeFilters();
});

/**
 * 初始化事件监听器
 */
function initializeEventListeners() {
    // 搜索框事件
    const searchInput = document.getElementById('search-input');
    const searchClear = document.getElementById('search-clear');
    
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleSearch, 300));
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                handleSearch();
            }
        });
    }
    
    if (searchClear) {
        searchClear.addEventListener('click', clearSearch);
    }
    
    // 筛选器事件
    document.querySelectorAll('.filter-select').forEach(select => {
        select.addEventListener('change', handleFilterChange);
    });
    
    // 重置筛选器
    const resetBtn = document.getElementById('reset-filters');
    if (resetBtn) {
        resetBtn.addEventListener('click', resetFilters);
    }
    
    // 表格排序
    document.querySelectorAll('.sortable').forEach(th => {
        th.addEventListener('click', handleSort);
    });
    
    // 视图切换
    document.querySelectorAll('.view-btn').forEach(btn => {
        btn.addEventListener('click', handleViewChange);
    });
    
    // 页面大小选择
    const pageSizeSelect = document.getElementById('page-size');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', handlePageSizeChange);
    }
    
    // 新增客户按钮
    const addCustomerBtn = document.getElementById('add-customer-btn');
    if (addCustomerBtn) {
        addCustomerBtn.addEventListener('click', () => {
            window.location.href = 'customer-form.html';
        });
    }
    
    // 导入按钮
    const importBtn = document.getElementById('import-btn');
    if (importBtn) {
        importBtn.addEventListener('click', handleImport);
    }
    
    // 导出按钮
    const exportBtn = document.getElementById('export-btn');
    if (exportBtn) {
        exportBtn.addEventListener('click', handleExport);
    }
    
    // 模态框关闭
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('modal-overlay')) {
            closeModal(e.target);
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal-overlay.show');
            if (openModal) {
                closeModal(openModal);
            }
        }
    });
}

/**
 * 防抖函数
 */
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

/**
 * 初始化搜索功能
 */
function initializeSearch() {
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        // 搜索框焦点效果
        searchInput.addEventListener('focus', function() {
            this.closest('.search-box').classList.add('focused');
        });
        
        searchInput.addEventListener('blur', function() {
            this.closest('.search-box').classList.remove('focused');
        });
    }
}

/**
 * 处理搜索
 */
function handleSearch() {
    const searchInput = document.getElementById('search-input');
    const searchTerm = searchInput.value.trim();
    
    // 更新URL参数
    const url = new URL(window.location);
    if (searchTerm) {
        url.searchParams.set('search', searchTerm);
    } else {
        url.searchParams.delete('search');
    }
    window.history.replaceState({}, '', url);
    
    // 重新加载数据
    currentPage = 1;
    loadCustomerList();
}

/**
 * 清除搜索
 */
function clearSearch() {
    const searchInput = document.getElementById('search-input');
    searchInput.value = '';
    
    // 移除URL参数
    const url = new URL(window.location);
    url.searchParams.delete('search');
    window.history.replaceState({}, '', url);
    
    // 重新加载数据
    currentPage = 1;
    loadCustomerList();
}

/**
 * 初始化筛选器
 */
function initializeFilters() {
    // 从URL读取筛选参数
    const url = new URL(window.location);
    
    document.querySelectorAll('.filter-select').forEach(select => {
        const paramName = select.id.replace('-filter', '');
        const paramValue = url.searchParams.get(paramName);
        if (paramValue) {
            select.value = paramValue;
            currentFilters[paramName] = paramValue;
        }
    });
}

/**
 * 处理筛选器变化
 */
function handleFilterChange(e) {
    const filterId = e.target.id;
    const filterName = filterId.replace('-filter', '');
    const filterValue = e.target.value;
    
    // 更新筛选状态
    if (filterValue) {
        currentFilters[filterName] = filterValue;
    } else {
        delete currentFilters[filterName];
    }
    
    // 更新URL参数
    const url = new URL(window.location);
    if (filterValue) {
        url.searchParams.set(filterName, filterValue);
    } else {
        url.searchParams.delete(filterName);
    }
    window.history.replaceState({}, '', url);
    
    // 重新加载数据
    currentPage = 1;
    loadCustomerList();
}

/**
 * 重置筛选器
 */
function resetFilters() {
    // 清除筛选状态
    currentFilters = {};
    
    // 重置表单
    document.querySelectorAll('.filter-select').forEach(select => {
        select.value = '';
    });
    
    // 清除搜索
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.value = '';
    }
    
    // 更新URL
    const url = new URL(window.location);
    url.search = '';
    window.history.replaceState({}, '', url);
    
    // 重新加载数据
    currentPage = 1;
    loadCustomerList();
}

/**
 * 处理表格排序
 */
function handleSort(e) {
    const th = e.currentTarget;
    const field = th.getAttribute('data-sort');
    
    // 切换排序方向
    if (currentSort.field === field) {
        currentSort.order = currentSort.order === 'asc' ? 'desc' : 'asc';
    } else {
        currentSort.field = field;
        currentSort.order = 'asc';
    }
    
    // 更新排序图标
    updateSortIcons();
    
    // 重新加载数据
    loadCustomerList();
}

/**
 * 更新排序图标
 */
function updateSortIcons() {
    document.querySelectorAll('.sortable i').forEach(icon => {
        icon.className = 'fas fa-sort';
    });
    
    const currentTh = document.querySelector(`[data-sort="${currentSort.field}"]`);
    if (currentTh) {
        const icon = currentTh.querySelector('i');
        icon.className = currentSort.order === 'asc' ? 'fas fa-sort-up' : 'fas fa-sort-down';
    }
}

/**
 * 处理视图切换
 */
function handleViewChange(e) {
    const btn = e.currentTarget;
    const viewType = btn.getAttribute('data-view');
    
    // 更新按钮状态
    document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    
    // 切换视图
    if (viewType === 'grid') {
        showGridView();
    } else {
        showTableView();
    }
}

/**
 * 显示表格视图
 */
function showTableView() {
    const tableContainer = document.getElementById('table-view');
    const gridContainer = document.getElementById('grid-view');
    
    // 平滑切换动画
    if (gridContainer) {
        gridContainer.classList.add('fade-out');
        setTimeout(() => {
            gridContainer.style.display = 'none';
            gridContainer.classList.remove('fade-out');
        }, 150);
    }
    
    if (tableContainer) {
        setTimeout(() => {
            tableContainer.style.display = 'block';
            tableContainer.classList.add('fade-out');
            setTimeout(() => {
                tableContainer.classList.remove('fade-out');
            }, 10);
        }, 150);
    }
}

/**
 * 显示网格视图
 */
function showGridView() {
    const tableContainer = document.getElementById('table-view');
    const gridContainer = document.getElementById('grid-view');
    
    // 平滑切换动画
    if (tableContainer) {
        tableContainer.classList.add('fade-out');
        setTimeout(() => {
            tableContainer.style.display = 'none';
            tableContainer.classList.remove('fade-out');
        }, 150);
    }
    
    if (gridContainer) {
        setTimeout(() => {
            gridContainer.style.display = 'block';
            gridContainer.classList.add('fade-out');
            setTimeout(() => {
                gridContainer.classList.remove('fade-out');
            }, 10);
        }, 150);
    }
    
    // 渲染网格数据
    renderGridView();
}

/**
 * 处理页面大小变化
 */
function handlePageSizeChange(e) {
    pageSize = parseInt(e.target.value);
    currentPage = 1;
    loadCustomerList();
}

/**
 * 加载客户列表
 */
function loadCustomerList() {
    // 构建请求参数
    const params = {
        page: currentPage,
        page_size: pageSize,
        sort_field: currentSort.field,
        sort_order: currentSort.order,
        ...currentFilters
    };
    
    // 添加搜索参数
    const searchInput = document.getElementById('search-input');
    if (searchInput && searchInput.value.trim()) {
        params.search = searchInput.value.trim();
    }
    
    // 显示加载状态
    showLoading();
    
    // 模拟API调用（实际项目中替换为真实API）
    setTimeout(() => {
        const mockData = generateMockData();
        renderCustomerList(mockData);
        updatePagination(mockData.total);
        hideLoading();
    }, 500);
}

/**
 * 生成模拟数据
 */
function generateMockData() {
    const customers = [
        {
            id: 1,
            customer_number: 'CRM2025000001',
            name: '张大爷',
            gender: '男',
            age: 68,
            phone: '138****8001',
            status: '有效客户',
            health_status: '健康良好',
            tags: ['VIP客户', '身体健康'],
            created_at: '2025-01-15',
            photo_url: '' // 留空以使用占位符
        },
        {
            id: 2,
            customer_number: 'CRM2025000002',
            name: '李大妈',
            gender: '女',
            age: 65,
            phone: '139****8002',
            status: '潜在客户',
            health_status: '健康一般',
            tags: ['优质客户', '需要关怀'],
            created_at: '2025-01-14',
            photo_url: '' // 留空以使用占位符
        },
        {
            id: 3,
            customer_number: 'CRM2025000003',
            name: '王先生',
            gender: '男',
            age: 72,
            phone: '137****8003',
            status: '已成交客户',
            health_status: '健康较差',
            tags: ['普通客户', '需要照顾'],
            created_at: '2025-01-13',
            photo_url: '' // 留空以使用占位符
        }
    ];
    
    return {
        customers: customers,
        total: 1248,
        page: currentPage,
        page_size: pageSize
    };
}

/**
 * 渲染客户列表
 */
function renderCustomerList(data) {
    const tbody = document.getElementById('customer-table-body');
    if (tbody) {
        tbody.innerHTML = '';
        
        data.customers.forEach(customer => {
            const row = createCustomerRow(customer);
            tbody.appendChild(row);
        });
    }
    
    // 同时渲染网格视图
    renderGridView(data);
    
    // 更新结果计数
    const resultCount = document.querySelector('.result-count');
    if (resultCount) {
        resultCount.textContent = `共 ${data.total.toLocaleString()} 条记录`;
    }
}

/**
 * 渲染网格视图
 */
function renderGridView(data) {
    const gridBody = document.getElementById('customer-grid-body');
    if (!gridBody) return;
    
    // 如果没有传入数据，使用当前数据
    if (!data) {
        const mockData = generateMockData();
        data = mockData;
    }
    
    gridBody.innerHTML = '';
    
    data.customers.forEach(customer => {
        const card = createCustomerCard(customer);
        gridBody.appendChild(card);
    });
}

/**
 * 创建客户卡片
 */
function createCustomerCard(customer) {
    const card = document.createElement('div');
    card.className = 'customer-card';
    card.setAttribute('data-customer-id', customer.id);
    card.onclick = () => viewCustomer(customer.id);
    
    card.innerHTML = `
        <div class="card-header">
            <div class="customer-avatar large">${customer.name.charAt(0)}</div>
            <div class="customer-basic">
                <div class="customer-name">${customer.name}</div>
                <div class="customer-number">${customer.customer_number}</div>
            </div>
            <div class="card-actions">
                <button class="card-action-btn" title="编辑" onclick="editCustomer(${customer.id}, event)">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="card-action-btn" title="更多" onclick="showMoreActions(${customer.id}, event)">
                    <i class="fas fa-ellipsis-h"></i>
                </button>
            </div>
        </div>
        
        <div class="card-body">
            <div class="card-content">
                <div class="customer-info-section">
                    <div class="customer-meta">
                        <div class="meta-item">
                            <i class="fas fa-birthday-cake"></i>
                            <span>${customer.age}岁</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-phone"></i>
                            <span>${customer.phone}</span>
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-calendar"></i>
                            <span>${customer.created_at}</span>
                        </div>
                    </div>

                    <div class="customer-status">
                        <span class="status-badge ${getStatusClass(customer.status)}">${customer.status}</span>
                        <span class="health-badge ${getHealthClass(customer.health_status)}">${customer.health_status}</span>
                    </div>

                    <div class="customer-tags">
                        ${customer.tags.map(tag => `<span class="tag ${getTagClass(tag)}">${tag}</span>`).join('')}
                    </div>
                </div>
                
                <div class="customer-photo-section">
                    <div class="customer-photo">
                        <img src="${getCustomerPhotoUrl(customer)}" alt="${customer.name}" class="photo-img" onerror="this.style.opacity='0'">
                        <div class="photo-placeholder">
                            <i class="fas fa-user"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card-footer">
            <button class="card-footer-btn primary" onclick="callCustomer(${customer.id}, event)">
                <i class="fas fa-phone"></i>
                <span>拨打电话</span>
            </button>
            <button class="card-footer-btn secondary" onclick="sendMessage(${customer.id}, event)">
                <i class="fas fa-comment"></i>
                <span>发送短信</span>
            </button>
        </div>
    `;
    
    return card;
}

/**
 * 创建客户行
 */
function createCustomerRow(customer) {
    const row = document.createElement('tr');
    row.className = 'customer-row';
    row.setAttribute('data-customer-id', customer.id);
    
    row.innerHTML = `
        <td class="customer-number">${customer.customer_number}</td>
        <td class="customer-name">
            <div class="customer-info">
                <div class="customer-avatar">${customer.name.charAt(0)}</div>
                <div class="customer-details">
                    <div class="name">${customer.name}</div>
                    <div class="phone">${customer.phone}</div>
                </div>
            </div>
        </td>
        <td>
            <span class="gender-badge ${customer.gender === '男' ? 'male' : 'female'}">${customer.gender}</span>
        </td>
        <td>${customer.age}</td>
        <td>${customer.phone}</td>
        <td>
            <span class="status-badge ${getStatusClass(customer.status)}">${customer.status}</span>
        </td>
        <td>
            <span class="health-badge ${getHealthClass(customer.health_status)}">${customer.health_status}</span>
        </td>
        <td>
            <div class="tag-list">
                ${customer.tags.map(tag => `<span class="tag ${getTagClass(tag)}">${tag}</span>`).join('')}
            </div>
        </td>
        <td>${customer.created_at}</td>
        <td class="actions">
            <div class="action-buttons">
                <button class="action-btn" title="查看详情" onclick="viewCustomer(${customer.id})">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="action-btn" title="编辑" onclick="editCustomer(${customer.id})">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="action-btn" title="更多操作" onclick="showMoreActions(${customer.id})">
                    <i class="fas fa-ellipsis-h"></i>
                </button>
            </div>
        </td>
    `;
    
    return row;
}

/**
 * 获取状态样式类
 */
function getStatusClass(status) {
    const statusMap = {
        '有效客户': 'status-active',
        '潜在客户': 'status-potential',
        '已成交客户': 'status-deal',
        '无效客户': 'status-inactive',
        '黑名单': 'status-blacklist'
    };
    return statusMap[status] || 'status-default';
}

/**
 * 获取健康状况样式类
 */
function getHealthClass(health) {
    const healthMap = {
        '健康良好': 'health-good',
        '健康一般': 'health-normal',
        '健康较差': 'health-poor',
        '健康很差': 'health-bad'
    };
    return healthMap[health] || 'health-default';
}

/**
 * 获取标签样式类
 */
function getTagClass(tag) {
    const tagMap = {
        'VIP客户': 'tag-vip',
        '优质客户': 'tag-quality',
        '普通客户': 'tag-normal',
        '身体健康': 'tag-health',
        '需要关怀': 'tag-careful',
        '需要照顾': 'tag-care'
    };
    return tagMap[tag] || 'tag-default';
}

/**
 * 获取客户照片URL
 */
function getCustomerPhotoUrl(customer) {
    // 如果客户有真实照片URL，直接返回
    if (customer.photo_url && customer.photo_url.trim()) {
        return customer.photo_url;
    }
    
    // 生成不同颜色的占位符图片
    const colors = [
        { bg: 'E5E5EA', text: '8E8E93' }, // 灰色
        { bg: 'FFE4E1', text: 'CD5C5C' }, // 粉色
        { bg: 'E0F2F1', text: '26A69A' }, // 青色
        { bg: 'E8F5E8', text: '4CAF50' }, // 绿色
        { bg: 'FFF3E0', text: 'FF9800' }, // 橙色
        { bg: 'E3F2FD', text: '2196F3' }, // 蓝色
        { bg: 'F3E5F5', text: '9C27B0' }, // 紫色
        { bg: 'FFF8E1', text: 'FFC107' }  // 黄色
    ];
    
    // 根据客户ID选择颜色
    const colorIndex = customer.id % colors.length;
    const color = colors[colorIndex];
    
    // 获取客户姓名首字符
    const firstChar = customer.name.charAt(0);
    
    // 生成占位符图片URL
    return `https://via.placeholder.com/80x80/${color.bg}/${color.text}?text=${encodeURIComponent(firstChar)}`;
}

/**
 * 更新分页
 */
function updatePagination(total) {
    const totalPages = Math.ceil(total / pageSize);
    const paginationInfo = document.querySelector('.pagination-info');
    const pagination = document.querySelector('.pagination');
    
    if (paginationInfo) {
        const start = (currentPage - 1) * pageSize + 1;
        const end = Math.min(currentPage * pageSize, total);
        paginationInfo.textContent = `显示第 ${start}-${end} 条，共 ${total.toLocaleString()} 条记录`;
    }
    
    if (pagination) {
        renderPagination(pagination, totalPages);
    }
}

/**
 * 渲染分页控件
 */
function renderPagination(container, totalPages) {
    container.innerHTML = '';
    
    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.className = 'page-btn';
    prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
    prevBtn.disabled = currentPage === 1;
    prevBtn.addEventListener('click', () => goToPage(currentPage - 1));
    container.appendChild(prevBtn);
    
    // 页码按钮
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = 'page-btn';
        pageBtn.textContent = i;
        pageBtn.classList.toggle('active', i === currentPage);
        pageBtn.addEventListener('click', () => goToPage(i));
        container.appendChild(pageBtn);
    }
    
    // 省略号和最后一页
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const dots = document.createElement('span');
            dots.className = 'page-dots';
            dots.textContent = '...';
            container.appendChild(dots);
        }
        
        const lastBtn = document.createElement('button');
        lastBtn.className = 'page-btn';
        lastBtn.textContent = totalPages;
        lastBtn.addEventListener('click', () => goToPage(totalPages));
        container.appendChild(lastBtn);
    }
    
    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.className = 'page-btn';
    nextBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.addEventListener('click', () => goToPage(currentPage + 1));
    container.appendChild(nextBtn);
}

/**
 * 跳转到指定页面
 */
function goToPage(page) {
    if (page >= 1) {
        currentPage = page;
        loadCustomerList();
    }
}

/**
 * 显示加载状态
 */
function showLoading() {
    // 可以添加加载动画
    console.log('Loading...');
}

/**
 * 隐藏加载状态
 */
function hideLoading() {
    console.log('Loading complete');
}

/**
 * 查看客户详情
 */
function viewCustomer(customerId) {
    window.location.href = `customer-detail.html?id=${customerId}`;
}

/**
 * 编辑客户
 */
function editCustomer(customerId, event) {
    if (event) {
        event.stopPropagation();
    }
    window.location.href = `customer-form.html?id=${customerId}`;
}

/**
 * 显示更多操作菜单
 */
function showMoreActions(customerId, event) {
    if (event) {
        event.stopPropagation();
    }
    currentCustomerId = customerId;
    const modal = document.getElementById('action-menu-modal');
    if (modal) {
        modal.classList.add('show');
    }
}

/**
 * 关闭操作菜单
 */
function closeActionMenu() {
    const modal = document.getElementById('action-menu-modal');
    if (modal) {
        modal.classList.remove('show');
    }
    currentCustomerId = null;
}

/**
 * 关闭模态框
 */
function closeModal(modal) {
    modal.classList.remove('show');
}

/**
 * 拨打电话
 */
function callCustomer(customerId, event) {
    if (event) {
        event.stopPropagation();
    }
    
    // 使用传入的customerId或当前选中的客户ID
    const targetCustomerId = customerId || currentCustomerId;
    
    if (targetCustomerId) {
        // 实现拨打电话逻辑
        showAlert('正在为您拨打客户电话...', 'info');
        if (currentCustomerId) {
            closeActionMenu();
        }
    }
}

/**
 * 发送短信
 */
function sendMessage(customerId, event) {
    if (event) {
        event.stopPropagation();
    }
    
    // 使用传入的customerId或当前选中的客户ID
    const targetCustomerId = customerId || currentCustomerId;
    
    if (targetCustomerId) {
        // 实现发送短信逻辑
        showAlert('正在打开短信发送界面...', 'info');
        if (currentCustomerId) {
            closeActionMenu();
        }
    }
}

/**
 * 添加备注
 */
function addNote() {
    if (currentCustomerId) {
        // 实现添加备注逻辑
        showAlert('正在打开备注编辑界面...', 'info');
        closeActionMenu();
    }
}

/**
 * 查看历史
 */
function viewHistory() {
    if (currentCustomerId) {
        // 实现查看历史逻辑
        window.location.href = `customer-history.html?id=${currentCustomerId}`;
        closeActionMenu();
    }
}

/**
 * 删除客户
 */
function deleteCustomer() {
    if (currentCustomerId) {
        if (confirm('确定要删除该客户吗？此操作不可撤销。')) {
            // 实现删除逻辑
            showAlert('客户删除成功', 'success');
            loadCustomerList();
        }
        closeActionMenu();
    }
}

/**
 * 处理导入
 */
function handleImport() {
    // 创建文件输入元素
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx,.xls,.csv';
    input.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            showAlert('正在导入客户数据...', 'info');
            // 实现文件导入逻辑
        }
    });
    input.click();
}

/**
 * 处理导出
 */
function handleExport() {
    // 实现导出逻辑
    showAlert('正在导出客户数据...', 'info');
    
    // 模拟导出
    setTimeout(() => {
        showAlert('客户数据导出成功', 'success');
    }, 2000);
}

/**
 * 显示提示信息
 */
function showAlert(message, type = 'info') {
    // 创建提示元素
    const alert = document.createElement('div');
    alert.className = `alert alert-${type}`;
    alert.innerHTML = `
        <i class="fas fa-${getAlertIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(alert);
    
    // 显示动画
    setTimeout(() => {
        alert.style.opacity = '1';
        alert.style.transform = 'translateY(0)';
    }, 10);
    
    // 自动移除
    setTimeout(() => {
        alert.style.opacity = '0';
        alert.style.transform = 'translateY(-20px)';
        setTimeout(() => {
            document.body.removeChild(alert);
        }, 300);
    }, 3000);
}

/**
 * 获取提示图标
 */
function getAlertIcon(type) {
    const iconMap = {
        'info': 'info-circle',
        'success': 'check-circle',
        'warning': 'exclamation-triangle',
        'error': 'times-circle'
    };
    return iconMap[type] || 'info-circle';
}

// 添加提示样式
const alertStyles = `
    .alert {
        position: fixed;
        top: 80px;
        right: 20px;
        z-index: 9999;
        opacity: 0;
        transform: translateY(-20px);
        transition: all 0.3s ease;
        max-width: 300px;
    }
`;

// 动态添加样式
const style = document.createElement('style');
style.textContent = alertStyles;
document.head.appendChild(style);